﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using iTunesLib;

namespace iTunesSync
{
    public partial class MainForm : Form
    {
        iTunesLib.iTunesApp iTunes;
        private delegate void addSongDelegate(ListViewItem item);
        private delegate void addSongsFinishedDelegate();
        private string[] whiteList;

        public MainForm()
        {
            InitializeComponent();
        }

        #region Form Events

        private void MainForm_Load(object sender, EventArgs e)
        {
            Settings.setPath(System.IO.Directory.GetCurrentDirectory());
            //
            iTunes = new iTunesApp();
            //
            if (!String.IsNullOrEmpty(Settings.syncPath))
            {
                textBox1.Text = Settings.syncPath; 
                loadSongs();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog findDir = new FolderBrowserDialog();
            findDir.Description = "Directory of the songs that where synced.";
            if (findDir.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = findDir.SelectedPath;
                Settings.syncPath = findDir.SelectedPath;
                loadSongs();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            runSync();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            loadSongs();
        }

        #endregion

        #region Load Songs

        private void loadSongs()
        {
            button2.Enabled = false;
            button3.Enabled = false;
            listView1.Items.Clear();
            new Thread(new ParameterizedThreadStart(loadSongsWorker)).Start();
        }

        private void loadSongsWorker(object obj)
        {
            if (String.IsNullOrEmpty(Settings.syncPath)) { return; }
            //
            string[] files = Directory.GetFiles(Settings.syncPath, "*.*", SearchOption.AllDirectories);
            foreach (string file in files)
            {
                string name = parseFileName(file);
                string ext = parseFileExtension(file);
                if (isInWhiteList(ext))
                {
                    ListViewItem item = new ListViewItem(new[] { name, ext, file });
                    item.Checked = true;
                    addSong(item);
                }
            }
            addSongsFinished();
        }

        private void addSong(ListViewItem item)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new addSongDelegate(addSong), new object[] { item });
                return;
            }
            //
            listView1.Items.Add(item);
        }

        private void addSongsFinished()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new addSongsFinishedDelegate(addSongsFinished), new object[] { });
                return;
            }
            //
            button2.Enabled = true;
            button3.Enabled = true;
        }

        #endregion

        #region Sync

        private void runSync()
        {
            button2.Enabled = false;
            ListView.ListViewItemCollection songs = listView1.Items;
            //count how many are checked for SyncStatus
            SyncStatus statusSync = new SyncStatus();
            statusSync.setTotal(listView1.CheckedItems.Count);
            statusSync.Show();
            //Sync
            foreach (ListViewItem song in songs)
            {
                if (song.Checked) { addToLibrary(song.SubItems[2].Text); statusSync.increaseCurrent(); }
            }
            button2.Enabled = true;
        }

        private void addToLibrary(string file)
        {
            IITTrackCollection tracks = iTunes.LibraryPlaylist.Tracks;
            foreach (IITTrack track in tracks)
            {
                //check against iTunes library before adding
                
            }
            iTunes.LibraryPlaylist.AddFile(file);
        }

        #endregion

        #region Whitelist

        private void loadWhiteList()
        {
            string parseMe = File.ReadAllText(Directory.GetCurrentDirectory() + "//supported.wl");
            whiteList = parseMe.Replace(" ", "").ToLower().Split(',');
        }

        private bool isInWhiteList(string extension)
        {
            if (whiteList == null) { loadWhiteList(); }
            string extToLower = extension.ToLower();
            foreach (string ext in whiteList)
            {
                if (extToLower == ext.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region Parse Functions

        private string parseFileName(string filePath, bool leaveExtension = false)
        {
            string fileName = filePath.Remove(0, filePath.LastIndexOf("\\") + 1);
            if (!leaveExtension) { fileName = fileName.Replace(parseFileExtension(fileName, true), ""); }
            return fileName;
        }

        private string parseFileExtension(string fileName, bool leavePeriod = false)
        {
            if (!leavePeriod) { return fileName.Remove(0, fileName.LastIndexOf('.') + 1); }
            else { return fileName.Remove(0, fileName.LastIndexOf('.')); }
        }

        #endregion

        private void button4_Click(object sender, EventArgs e)
        {
            new DuplicateDetector().Show();
        }
    }
}
